package com.eco.fanliapp.controller.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.base.BaseController;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.constant.WechatConfig;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.*;
import com.eco.fanliapp.dataoke.DaTaoKeConfig;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.fengou.FenGouItemInfoService;
import com.eco.fanliapp.jd.JDSearchController;
import com.eco.fanliapp.jd.JdOrderController;
import com.eco.fanliapp.pinduoduo.PDDSearchController;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.service.impl.SyModuleServiceImpl;
import com.eco.fanliapp.taobao.ItemInfoController;
import com.eco.fanliapp.taobao.SearchController;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.AppGoodsVo;
import com.eco.fanliapp.vo.HaoDanKuHotKeyInfo.KeyWord;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import com.eco.fanliapp.vo.HaoDanKuSuperClassifyInfo.GeneralClassify;
import com.eco.fanliapp.vo.TbkItemConvertInfo.TbkItemConvertData;
import com.eco.fanliapp.vo.TbkItemInfoGetInfo.NTbkItem;
import com.eco.fanliapp.vo.YoungmallItemInfo;
import com.eco.fanliapp.vo.respone.DTKResponse;
import com.eco.fanliapp.vo.respone.PDDGoodsPromotionUrlResponse;
import com.eco.fanliapp.vo.respone.ResponeFriendsResults;
import com.eco.fanliapp.vo.respone.ResponeOrderResults.OrderDataBean;
import com.eco.fanliapp.vo.respone.ResponeResults;
import com.google.common.base.Joiner;
import com.taobao.api.response.TbkItemInfoGetResponse;
import com.taobao.api.response.TbkScMaterialOptionalResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/mobile/home")
public class HaoDanKuController extends BaseController {

    @Autowired
    private ITaoBaoService taoBaoService;

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private IAppUserSearchHistoryService appUserSearchHistoryService;

    @Autowired
    private ISyTimePeriodAppointmentService syTimePeriodAppointmentService;

    @Autowired
    private ISyTimePeriodGoodsService syTimePeriodGoodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisTemplateService redisTemplateService;

    @Autowired
    private FenGouItemInfoService fenGouItemInfoService;
    @Autowired
    private SyChannelUserMapper syChannelUserMapper;
    @Autowired
    private IDwzService dwzService;

    @Autowired
    private ISyUserTaskService syUserTaskService;
    @Autowired
    private PDDSearchController pddSearchController;
    @Autowired
    private JdOrderController jdOrderController;
    @Autowired
    private ISyModuleService syModuleService;

    private static final Logger log = LoggerFactory.getLogger(HaoDanKuController.class);
    private ServerResponse<ResponeResults> response;

    /**
     * 关键词搜索
     *
     * @param keyword
     * @param shopid
     * @param back
     * @param sort
     * @param cid
     * @param min_id
     * @param price_min
     * @param price_max
     * @param sale_min
     * @param sale_max
     * @param coupon_min
     * @param coupon_max
     * @param type
     * @return
     */
    @GetMapping("/SearchKey")
    @ResponseBody
    public ServerResponse<ResponeResults> search(String keyword, String shopid, Integer back, Integer sort, Integer cid,
                                                 Integer min_id, Integer price_min, Integer price_max, Integer sale_min, Integer sale_max,
                                                 Integer coupon_min, Integer coupon_max, Integer type) {
        AppUser u = getAppUser();
        if (u == null) {
            return taoBaoService.getSearchKeyWord(keyword, shopid, back, sort, cid, min_id,
                    price_min, price_max, sale_min, sale_max, coupon_min, coupon_max, type, null);
        }
        return taoBaoService.getSearchKeyWord(keyword, shopid, back, sort, cid, min_id,
                price_min, price_max, sale_min, sale_max, coupon_min, coupon_max, type, getAppUser().getUserId());
    }

    /**
     * 淘宝API
     * 猜你喜欢
     *
     * @param itemId        获取猜你喜欢的类型商品的宝贝ID，可以优先获取相同二级类目下的商品
     * @param pageSize      页大小，默认20，1~100
     * @param pageNo        第几页，默认：1
     * @param deviceValue   设备号
     * @param deviceEncrypt 设备号加密类型：MD5
     * @param deviceType    设备号类型：IMEI，或者IDFA，或者UTDID
     * @return https://open.taobao.com/api.htm?docId=33947&docType=2&scopeId=11655
     */
    @GetMapping("/getSimilarInfo2")
    @ResponseBody
    public ServerResponse<ResponeResults> getSimilarInfo2(String itemId, String deviceValue, String deviceEncrypt,
                                                          String deviceType, Long pageSize, Long pageNo) {
        AppUser u = getAppUser();
        if (u == null) {
            return taoBaoService.getSimilarInfoMethon(itemId, deviceValue, deviceEncrypt, deviceType,
                    pageSize, pageNo, null);
        }
        return taoBaoService.getSimilarInfoMethon(itemId, deviceValue, deviceEncrypt, deviceType,
                pageSize, pageNo, getAppUser().getUserId());
    }

    /**
     * 热搜词--搜索页面
     *
     * @return
     */
    @GetMapping("/getSearchHotKey")
    @ResponseBody
    public ServerResponse getSearchHotKey() {
//        return taoBaoService.getSearchHotKey();//好单库
//        taoBaoService.getSearchHotKey();
        return taoBaoService.dtkHotSearch();//大淘客
    }

    /**
     * 热搜词
     *
     * @return
     */
    @GetMapping("/getHDKHotKey")
    @ResponseBody
    public ServerResponse getHDKHotKey() {
        return taoBaoService.getHDKHotKeyNew();
    }

    /**
     * 大家都搜了
     *
     * @return
     */
    @GetMapping("/getSearchKey")
    @ResponseBody
    public ServerResponse getSearchKey(String keyword) {
        return taoBaoService.getSearchKey(keyword);
    }

    /**
     * 获取首页类目-used
     *
     * @return
     */
    @GetMapping("/getClassify")
    @ResponseBody
    public ServerResponse<List<AppGoodsClassify>> getClassify() {
        return taoBaoService.getClassify();
    }

    /**
     * 首页二级类目-used
     *
     * @param cid
     * @param appVersion
     * @return
     */
    @GetMapping("/getSuperCategory")
    @ResponseBody
    public ServerResponse getSuperCategory(Integer cid, String appVersion) {

        return taoBaoService.getSuperCategory(cid, appVersion);
    }

    /**
     * 超级分类-used
     *
     * @return
     */
    @GetMapping("/getSuperClassify")
    @ResponseBody
    public ServerResponse<List<GeneralClassify>> getSuperClassify() {
        return taoBaoService.getSuperClassify();
    }


    /**
     * 根据首页类目查询商品列表
     *
     * @param type
     * @param pageNum
     * @param pageSize
     * @param cid
     * @param recommend
     * @param sort
     * @param free
     * @return
     */
    @GetMapping("/getClassifyItemList")
    @ResponseBody
    public ServerResponse<ResponeResults> getClassifyItemList(Integer type, Integer pageNum, Integer pageSize,
                                                              Integer cid, Integer recommend, @RequestParam(required = false, defaultValue = "") Integer sort,
                                                              @RequestParam(required = false, defaultValue = "false") Boolean free) {
        AppUser u = getAppUser();
        if (u == null || u.getUserId() == null) {
            return taoBaoService.getClassifyItemList(type, pageNum, pageSize, cid, recommend, sort, null, free, null);
        }
        AppUser appUser = appUserService.selectAppUserByUserId(u.getUserId());
        if (appUser == null || appUser.getUserId() == null) {
            return taoBaoService.getClassifyItemList(type, pageNum, pageSize, cid, recommend, sort, null, free, null);
        }

        return taoBaoService.getClassifyItemList(type, pageNum, pageSize, cid, recommend, sort, getAppUser().getUserId(), free,
                getAppUser().getCompanyId());
    }

    /**
     * 查询免单商品
     *
     * @param type
     * @param cid
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getGoodsFreeList")
    @ResponseBody
    public ServerResponse<ResponeResults> getGoodsFreeList(Integer type, Integer cid, Integer pageNum, Integer pageSize) {
        AppUser u = getAppUser();
        if (u == null || u.getUserId() == null) {
            return taoBaoService.getGoodsFreeList(type, cid, pageNum, pageSize, null, null);
        }
        AppUser appUser = appUserService.selectAppUserByUserId(u.getUserId());
        if (appUser == null || appUser.getUserId() == null) {
            return taoBaoService.getGoodsFreeList(type, cid, pageNum, pageSize, null, null);
        }

        return taoBaoService.getGoodsFreeList(type, cid, pageNum, pageSize, getAppUser().getUserId(),
                getAppUser().getCompanyId());
    }

    /**
     * 根据商品ID获取商品详情
     *
     * @param itemId
     * @return
     */
    @GetMapping("/getSearchItemIdDetail")
    @ResponseBody
    public ServerResponse<List<NTbkItem>> getSearchItemIdDetail(String itemId) {
        return taoBaoService.getSearchItemIdDetail(itemId);
    }

    /**
     * @param itemId 商品id
     * @param isKill 是否是秒杀商品
     * @return
     */
    @GetMapping("/getHdkSearchItemIdDetail")
    @ResponseBody
    public ServerResponse getHdkSearchItemIdDetail(HttpServletRequest request, String itemId, @RequestParam(defaultValue = "0") Integer isKill, String activityId, String activityid) {
        if (!StringUtils.isEmpty(activityid)) {
            activityId = activityid;
        }
        String version = request.getHeader("version");
        AppUser u = getAppUser();
        Map map = new HashMap<>();
        map.put("min_id", null);
        ServerResponse<ResponeResults> response = null;
        if (u == null || u.getUserId() == null) {
            response = taoBaoService.getHdkSearchItemIdDetail(itemId, null, null, "0", null, activityId);
        } else if (u.getUserId() != null) {
            AppUser appUser = appUserService.selectAppUserByUserId(u.getUserId(), 1);
            if (appUser == null || appUser.getUserId() == null) {
                response = taoBaoService.getHdkSearchItemIdDetail(itemId, null, null, "0", null, activityId);
            } else {
                response = taoBaoService.getHdkSearchItemIdDetail(itemId, getAppUser().getUserId(), u.getChannelUserId(), "0", null, activityId);
            }
        } else {
            response = taoBaoService.getHdkSearchItemIdDetail(itemId, getAppUser().getUserId(), u.getChannelUserId(), "0", null, activityId);
        }
        if (response != null && response.getData() != null && response.getData().getMin_id() != null && response.getData().getMin_id() == 601) {
            return ServerResponse.createBySuccessCodeMessage(601, "商品已下架");
        }
        List<AppGoodsVo> appGoodsVoList = taoBaoService.getAppGoodsVo(null, null, response.getData(), null, version);
        map.put("data", appGoodsVoList);
        if (appGoodsVoList.size() > 0) {
            return ServerResponse.createBySuccess(map);
        }
        return ServerResponse.createBySuccess(201, "暂无数据", map);
    }

    /**
     * 根据商品ID进行高佣转链
     *
     * @param itemId
     * @param jumpType
     * @return
     */
    @GetMapping("/getPrivilegeItemId")
    @ResponseBody
    public ServerResponse<String> getPrivilegeItemId(String itemId, Integer jumpType, String activityId, String activityid) {
        if (!StringUtils.isEmpty(activityid)) {
            activityId = activityid;
        }
        AppUser u = getAppUser();
        if (u == null || u.getUserId() == null) {
            return taoBaoService.getPrivilegeItemURL(itemId, null, jumpType, activityId);
        }
        AppUser appUser = appUserService.selectAppUserByUserId(u.getUserId());
        if (appUser == null || appUser.getUserId() == null) {
            return taoBaoService.getPrivilegeItemURL(itemId, null, jumpType, activityId);
        }
        return taoBaoService.getPrivilegeItemURL(itemId, getAppUser().getUserId(), jumpType, activityId);
    }

    /**
     * 根据商品ID进行高佣转链(双十一，文豪用)
     *
     * @param itemId
     * @param jumpType
     * @return
     */
//    @GetMapping("/getPrivilegeItemIdNew")
//    @ResponseBody
//    public ServerResponse<String> getPrivilegeItemIdNew(String itemId, Integer jumpType) {
//        AppUser u = getAppUser();
//        if (u == null || u.getUserId() == null) {
//            return taoBaoService.getPrivilegeItemURL(itemId, null, jumpType);
//        }
//        AppUser appUser = appUserService.selectAppUserByUserId(u.getUserId());
//        if (appUser == null || appUser.getUserId() == null) {
//            return taoBaoService.getPrivilegeItemURL(itemId, null, jumpType);
//        }
//        return taoBaoService.getPrivilegeItemURL(itemId, getAppUser().getUserId(), jumpType);
//    }

    /**
     * 根据商品ID进行高佣转链
     *
     * @param itemId
     * @param jumpType
     * @return
     */
    @GetMapping("/getPrivilegeGoodsFreeItemId")
    @ResponseBody
    public ServerResponse<String> getPrivilegeGoodsFreeItemId(String itemId, Integer jumpType, String type, String activityId, String activityid) { //type ：1免单 2积分兑换
        if (!StringUtils.isEmpty(activityid)) {
            activityId = activityid;
        }
        AppUser u = getAppUser();
        if (u == null || u.getUserId() == null) {
            return taoBaoService.getPrivilegeGoodsFreeItemURL(itemId, null, jumpType, type, activityId);
        }
        AppUser appUser = appUserService.selectAppUserByUserId(u.getUserId(), 1);
        if (appUser == null || appUser.getUserId() == null) {
            return taoBaoService.getPrivilegeGoodsFreeItemURL(itemId, null, jumpType, type, activityId);
        }
        return taoBaoService.getPrivilegeGoodsFreeItemURL(itemId, getAppUser().getUserId(), jumpType, type, activityId);
    }

    /**
     * 解析淘口令
     *
     * @param tkl
     * @return
     */
    @GetMapping("/TaobaoAnalyzeTkl")
    @ResponseBody
    public ServerResponse<TbkItemConvertData> TaobaoAnalyzeTkl(String tkl) {

        return taoBaoService.TaobaoAnalyzeTkl(tkl);
    }

    /**
     * 生成淘口令
     *
     * @param itemId
     * @param itemTitle
     * @param itemPic
     * @param shareUrl
     * @return
     */
    @GetMapping("/TaobaoCreateTkl")
    @ResponseBody
    public ServerResponse<String> TaobaoCreateTkl(String itemId, String itemTitle, String itemPic, String shareUrl) {
        AppUser u = getAppUser();
        if (u == null) {
            return taoBaoService.TaobaoCreateTklNew(itemId, itemTitle, itemPic, shareUrl, null);
        }
        return taoBaoService.TaobaoCreateTklNew(itemId, itemTitle, itemPic, shareUrl, getAppUser().getUserId());
    }

    /**
     * 生成淘口令
     *
     * @param itemTitle
     * @param itemPic
     * @param couponUrl
     * @return
     */
    @GetMapping("/TaobaoCreateTklOld")
    @ResponseBody
    public ServerResponse<String> TaobaoCreateTklOld(String itemTitle, String itemPic, String couponUrl) {
        AppUser u = getAppUser();
        if (u == null) {
            return taoBaoService.TaobaoCreateTkl(itemTitle, itemPic, couponUrl, null);
        }
        return taoBaoService.TaobaoCreateTkl(itemTitle, itemPic, couponUrl, getAppUser().getUserId());
    }

    /**
     * 生成淘口令(双十一，文豪用)
     *
     * @param itemTitle
     * @param itemPic
     * @param couponUrl
     * @return
     */
    @PostMapping("/TaobaoCreateTklNew")
    @ResponseBody
    public ServerResponse<String> TaobaoCreateTklNew(String itemTitle, String itemPic, String couponUrl) {
        AppUser u = getAppUser();
        if (u == null) {
            return taoBaoService.TaobaoCreateTkl(itemTitle, itemPic, couponUrl, null);
        }
        return taoBaoService.TaobaoCreateTkl(itemTitle, itemPic, couponUrl, getAppUser().getUserId());
    }

    /**
     * 首页弹窗--旧
     *
     * @param str  内容
     * @param type 类型1标题查询淘口令查询3商品ID查询
     * @return
     */
    @GetMapping("/getPopup")
    @ResponseBody
    public ServerResponse<ResponeResults> Popup(String str, Integer type) {
        AppUser u = getAppUser();
        if (u == null) {
            return taoBaoService.Popup(str, type, null);
        }
        return taoBaoService.Popup(str, type, getAppUser().getUserId());
    }

    /**
     * 新-首页弹窗搜索--废弃
     *
     * @param str  内容
     * @param type 类型1标题查询淘口令查询3商品ID查询
     * @return
     */
    @GetMapping("/getPopupSearch")
    @ResponseBody
    public ServerResponse popupSearch(HttpServletRequest request, String str, Integer type//,Long pageNum,Long pageSize
            , @RequestParam(defaultValue = "1") Long pageNum, @RequestParam(defaultValue = "20") Long pageSize
    ) {
        String version = request.getHeader("version");
        AppUser u = getAppUser();
        if (u == null) {
            ServerResponse<ResponeResults> response = taoBaoService.popupSearch(str, type, null, pageNum, pageSize, null);

            List<AppGoodsVo> appGoodsVoList = taoBaoService.getAppGoodsVo(null, null, response.getData(), null, version);
            Map map = new HashMap<>();

            if (response.getStatus() == 201) {
                return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
            }
            map.put("min_id", null);
            map.put("data", appGoodsVoList);
            map.put("popType", response.getData().getPopType());
            return ServerResponse.createBySuccess(map);
        }
        ServerResponse<ResponeResults> response = taoBaoService.popupSearch(str, type, u.getUserId(), pageNum, pageSize, u.getChannelUserId());
        Map map = new HashMap<>();
        if (response != null && response.getData() != null && "a".equalsIgnoreCase(response.getData().getPopType())) {//是精准搜索
            Long userId = u.getUserId();
            String itemId = response.getData().getData().get(0).getItemId();
            QueryWrapper<AppUserSearchHistory> searchHistoryQueryWrapper = new QueryWrapper<AppUserSearchHistory>();
            searchHistoryQueryWrapper.eq("user_id", userId).eq("item_id", itemId);
            int count = appUserSearchHistoryService.count(searchHistoryQueryWrapper);
            AppUserSearchHistory appUserSearchHistory = new AppUserSearchHistory();
            if (count <= 0) {
                appUserSearchHistory.setUserId(userId);
                appUserSearchHistory.setSearchCount(1);
                appUserSearchHistory.setItemId(Long.parseLong(itemId));
                appUserSearchHistoryService.save(appUserSearchHistory);
            }
        }
        if (response != null && response.getData() != null) {
            List<AppGoodsVo> appGoodsVoList = taoBaoService.getAppGoodsVo(null, null, response.getData(), null, version);
            map.put("min_id", null);
            map.put("data", appGoodsVoList);
            map.put("popType", response.getData().getPopType());
        }
        if (map == null || map.size() == 0) {
            return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
        }
        return ServerResponse.createBySuccess(map);
    }

    /**
     * 新-首页弹窗搜索
     *
     * @param str 内容
     * @return
     */

    @RequestMapping("/getPopupSearchNew")
    @ResponseBody
    public ServerResponse getPopupSearchNew(HttpServletRequest request, String str, @RequestParam(defaultValue = "1") Long pageNum, @RequestParam(defaultValue = "20") Long pageSize
    ) {
        String version = request.getHeader("version");
        AppUser u = getAppUser();
        if (u == null) {
            ServerResponse<ResponeResults> response = taoBaoService.popupSearchNew(str, null, pageNum, pageSize, null);
            if (response != null && response.getStatus() == 400) {
                return ServerResponse.createBySuccessCodeMessage(402, "参数有误");
            }
            List<AppGoodsVo> appGoodsVoList = taoBaoService.getAppGoodsVo(null, null, response.getData(), null, version);
            Map map = new HashMap<>();

            if (response.getStatus() == 201) {
                return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
            }
            map.put("min_id", null);
            map.put("data", appGoodsVoList);
            map.put("popType", response.getData().getPopType());
            map.put("popupType", response.getData().getPopupType());
            return ServerResponse.createBySuccess(map);
        }
        ServerResponse<ResponeResults> response = taoBaoService.popupSearchNew(str, u.getUserId(), pageNum, pageSize, u.getChannelUserId());
        if (response != null && response.getStatus() == 400) {
            return ServerResponse.createBySuccessCodeMessage(402, "参数有误");
        }
        //是精准搜索
        if (response != null && response.getData() != null && "a".equalsIgnoreCase(response.getData().getPopType())) {
            String userId = u.getUserId().toString();
            String itemId = response.getData().getData().get(0).getItemId();
            //存redis
            Calendar cale = Calendar.getInstance();
            int hour = cale.get(Calendar.HOUR_OF_DAY);
            if (redisTemplate.hasKey("AppUserSearchHistory_" + hour)) {
                HashMap<String, Set<String>> mapSearch = (HashMap) redisTemplate.opsForValue().get("AppUserSearchHistory_" + hour);
                if (mapSearch.get(userId) != null) {
                    Set<String> userSet = mapSearch.get(userId);
                    userSet.add(itemId);
                    mapSearch.put(userId, userSet);
                } else {
                    Set<String> userSet = new HashSet<>();
                    userSet.add(itemId);
                    mapSearch.put(userId, userSet);
                }
                redisTemplate.opsForValue().set("AppUserSearchHistory_" + hour, mapSearch, 2, TimeUnit.HOURS);
            } else {
                HashMap<String, Set<String>> mapSearch = new HashMap<>();
                Set<String> userSet = new HashSet<>();
                userSet.add(itemId);
                mapSearch.put(userId, userSet);
                redisTemplate.opsForValue().set("AppUserSearchHistory_" + hour, mapSearch, 2, TimeUnit.HOURS);
            }
        }
        Map map = new HashMap<>();
        if (response != null && response.getData() != null) {
            List<AppGoodsVo> appGoodsVoList = taoBaoService.getAppGoodsVo(null, null, response.getData(), null, version);
            map.put("min_id", null);
            map.put("data", appGoodsVoList);
            map.put("popType", response.getData().getPopType());
            map.put("popupType", response.getData().getPopupType());
        }
        if (map == null || map.size() == 0) {
            return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
        }
        return ServerResponse.createBySuccess(map);

    }

    /**
     * ECO API
     * 超级搜索
     *
     * @param keyword  商品标题
     * @param sort     排序方式
     * @param pageSize 页大小，默认20，1~100
     * @param pageNum  第几页，默认：１
     * @return
     */
    @GetMapping("/SearchSuperTitle")
    @ResponseBody
    public ServerResponse<ResponeResults> SearchSuperTitle(String keyword, String sort, Long pageSize, Long pageNum,
                                                           @RequestParam(required = false, defaultValue = "false") Boolean hasCoupon) {
        AppUser u = getAppUser();
        if (u == null) {
            return taoBaoService.ReturnSearchSuperTitle(keyword, sort, pageSize, pageNum, null, true, null, null, "1");
        }
        return taoBaoService.ReturnSearchSuperTitle(keyword, sort, pageSize, pageNum, getAppUser().getUserId(), true, u.getChannelUserId(), null, "1");
    }

    /**
     * ECO API
     * 超级搜索 --大淘客
     *
     * @param keyword  商品标题
     * @param sort     排序方式
     * @param pageSize 页大小，默认20，1~100
     * @param pageNum  第几页，默认：１
     * @return
     */
    @GetMapping("/getDTKSearch")
    @ResponseBody
    public ServerResponse<ResponeResults> getDTKSearch(HttpServletRequest request, String keyword, @RequestParam(defaultValue = "") String sort, @RequestParam(defaultValue = "20") Long pageSize, @RequestParam(defaultValue = "1") Long pageNum, @RequestParam(defaultValue = "") Boolean hasCoupon, @RequestParam(defaultValue = "1") Integer type) {
        String version = request.getHeader("version");
        AppUser u = getAppUser();
        if (u == null) {
            return taoBaoService.ReturnSearchSuperTitle(keyword, sort, pageSize, pageNum, null, hasCoupon, null, version, type.toString());
        }
        return taoBaoService.ReturnSearchSuperTitle(keyword, sort, pageSize, pageNum, getAppUser().getUserId(), hasCoupon, u.getChannelUserId(), version, type.toString());
    }

    /**
     * 新—商品搜索
     *
     * @param keyword  商品标题
     * @param sort     排序方式
     * @param pageSize 页大小，默认20
     * @param pageNum  第几页，默认：１
     * @return
     */
    @GetMapping("/SearchLocalGoods")
    @ResponseBody
    public ServerResponse<ResponeResults> SearchLocalGoods(String keyword, String sort, @RequestParam(defaultValue = "20") Integer pageSize, @RequestParam(defaultValue = "1") Integer pageNum, String fqcat) {

        AppUser u = getAppUser();
        if (u == null) {
            return taoBaoService.SearchLocalGoods(keyword, sort, pageSize, pageNum, null, fqcat, null);
        }
        return taoBaoService.SearchLocalGoods(keyword, sort, pageSize, pageNum, getAppUser().getUserId(), fqcat, u.getChannelUserId());
    }

    /**
     * 商品搜索匹配列表
     *
     * @param keyword 商品标题
     * @return
     */
    @GetMapping("/findKeyword")
    @ResponseBody
    public ServerResponse<ResponeResults> findKeyword(String keyword) {

        return taoBaoService.findKeyword(keyword);
    }

    /**
     * 商品推荐列表--旧-已废弃
     *
     * @param pageSize 页大小，默认20
     * @param pageNum  第几页，默认：１
     * @return
     */
    @GetMapping("/getRecommendGoods")
    @ResponseBody
    public ServerResponse<ResponeResults> getRecommendGoods(HttpServletRequest request, @RequestParam(defaultValue = "20") Integer pageSize, @RequestParam(defaultValue = "1") Integer pageNum) {
        String version = request.getHeader("version");
        AppUser u = getAppUser();
        if (u == null) {
            return taoBaoService.getRecommendGoodsNew(pageSize, pageNum, null, null, version);
        }
        return taoBaoService.getRecommendGoodsNew(pageSize, pageNum, getAppUser().getUserId(), u.getChannelUserId(), version);
    }

    /**
     * 新—商品列表
     *
     * @param pageSize 页大小，默认20
     * @param pageNum  第几页，默认：１
     * @param cid      分类id
     * @param sort     排序
     * @param type     商品筛选类型
     * @return
     */
    @GetMapping("/getClassifyGoodsList")
    @ResponseBody
    public ServerResponse getClassifyGoodsList(HttpServletRequest request, @RequestParam(defaultValue = "20") Integer pageSize, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "0") Integer cid, @RequestParam(required = false, defaultValue = "updateTime") String sort, Integer type) {
        String version = request.getHeader("version");
        AppUser u = getAppUser();
        if (u == null) {
            if (cid == 0) {
                return taoBaoService.getRecommendGoodsNew(pageSize, pageNum, null, null, version);
            }
            return taoBaoService.getClassifyGoodsListNew(pageSize, pageNum, cid, sort, type, null, null, version);
        }
        if (cid == 0) {
            return taoBaoService.getRecommendGoodsNew(pageSize, pageNum, getAppUser().getUserId(), u.getChannelUserId(), version);
        }
        return taoBaoService.getClassifyGoodsListNew(pageSize, pageNum, cid, sort, type, getAppUser().getUserId(), u.getChannelUserId(), version);
    }

    /**
     * 获取榜单商品
     *
     * @return
     */
    @GetMapping("/getSaleslist")
    @ResponseBody
    public ServerResponse<ResponeResults> sales_list() {

        return taoBaoService.getSalesList();
    }

    /**
     * 获取我的订单
     * 支持到版本2.3.1之前
     *
     * @param tkStatus
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getMeOrderDetail")
    @ResponseBody
    public ServerResponse<List<OrderDataBean>> getMeOrderDetail(HttpServletRequest request, Integer tkStatus, Integer pageNum, Integer pageSize, String orderType) {
        String version = request.getHeader("version");
        ServerResponse<List<OrderDataBean>> data = taoBaoService.getMeOrderDetail(tkStatus, pageNum, pageSize, getAppUser().getUserId(), orderType, version);
        List<OrderDataBean> meBookedOrderDetail = data.getData();
        if (meBookedOrderDetail != null && meBookedOrderDetail.size() > 0) {
            for (OrderDataBean order : meBookedOrderDetail) {
                if (order.getOrderStatus() != null && ("12".equals(order.getOrderStatus()) || "22".equals(order.getOrderStatus()))) {
                    order.setOrderStatus("15");
                }
            }
        }
        return data;
    }

    /**
     * 获取我的订单-used
     *
     * @param tkStatus
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getMeOrderDetailNew")
    @ResponseBody
    public ServerResponse<List<OrderDataBean>> getMeOrderDetailNew(HttpServletRequest request, Integer tkStatus, Integer pageNum, Integer pageSize, @RequestParam(defaultValue = "1") Integer orderType) {
        String version = request.getHeader("version");
        AppUser u = getAppUser();
        if (null == u || u.getUserId() == null) {
            return ServerResponse.createByErrorCodeMessage(301, "Token不正确");
        }
        return taoBaoService.getMeOrderDetail(tkStatus, pageNum, pageSize, getAppUser().getUserId(), orderType.toString(), version);
    }

    /**
     * 获取我的收益-入账中订单-包含自己订单，直接粉丝订单，间接粉丝订单，分享赚订单     tkStatus = 12
     * 支持到版本2.3.1之前
     *
     * @param tkStatus
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getMeBookedOrderDetail")
    @ResponseBody
    public ServerResponse<List<OrderDataBean>> getMeBookedOrderDetail(Integer tkStatus, Integer pageNum, Integer pageSize) {

        return taoBaoService.getMeBookedOrderDetail(tkStatus, pageNum, pageSize, getAppUser().getUserId());
    }

    /**
     * 我的订单-很据订单编号查询
     *
     * @param orderId
     * @return
     */
    @GetMapping("/findOrderIdDetail")
    @ResponseBody
    public ServerResponse<List<OrderDataBean>> findOrderIdDetail(String orderId) {

        return taoBaoService.findOrderIdDetail(orderId, getAppUser().getUserId());
    }

    /**
     * 商品详情分享
     *
     * @param itemId
     * @return
     */
    @GetMapping("/shareGoods")
    @ResponseBody
    public ServerResponse<String> shareGoods(String itemId) {
//        String meInviteCode = getAppUser().getMeInviteCode();
        Long userId = getAppUser().getUserId();
        try {

            //type=5  邀请赚钱
            //type=1  详情分享
//            String str = "itemId=" + itemId + "&type=1&jumpType=1&linkType=0" + "&invitedCode=" + meInviteCode;
//            String data = "shengya!!!" + str + "shengya!!!";
//            String redirectUrl = WechatConfig.SNS_SHARE_URL + "?id=" + itemId + "&type=1&jumpType=1&linkType=0" + "&invitedCode" + meInviteCode + "&str=" + URLEncoder.encode(data, "UTF-8");
            String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WechatConfig.APPID + "&redirect_uri=" + WechatConfig.RETURNURL + "&response_type=code&scope=snsapi_userinfo&state=goods:" + userId + ":" + itemId + "#wechat_redirect";
            taoBaoService.getFriendsCount(Long.valueOf(itemId));

            return ServerResponse.createBySuccess("数据获取成功", dwzService.getShorUrl(redirectUrl));

        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 商品详情分享--used
     *
     * @param itemId
     * @return
     */
    @GetMapping("/shareGoodsNew")
    @ResponseBody
    public ServerResponse<String> shareGoodsNew(String itemId) {
        String meInviteCode = getAppUser().getMeInviteCode();
//        try {
//            String redirectUrl = ApiEnum.APP_SHARE_URL + "/mobile/home/pages/h5/url" + "?id=" + itemId + "&type=1"
//                    + "&invitedCode=" + meInviteCode
//                    + "&userName=" + ""
//                    + "&userUrl=" + "";
//            taoBaoService.getFriendsCount(Long.valueOf(itemId));
//            return ServerResponse.createBySuccess("数据获取成功", dwzService.getShorUrl(redirectUrl));
        Long userId = getAppUser().getUserId();
        try {

            String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WechatConfig.APPID + "&redirect_uri=" + WechatConfig.RETURNURL + "&response_type=code&scope=snsapi_userinfo&state=goods:" + userId + ":" + itemId + ":" + ":" + meInviteCode + "#wechat_redirect";
            taoBaoService.getFriendsCount(Long.valueOf(itemId));

            return ServerResponse.createBySuccess("数据获取成功", dwzService.getShorUrl(redirectUrl));


        } catch (Exception e) {
        }
        return null;
    }


    @RequestMapping("/pages/h5/url")
    public String url(String id, String type, String invitedCode, String userName, String userUrl) {
        String redirectUrl = null;
        try {
            if ("1".equals(type)) {
                String str = "itemId=" + id + "&type=1&jumpType=1&linkType=0" + "&invitedCode=" + invitedCode;
                String data = "shengya!!!" + str + "shengya!!!";
                redirectUrl = WechatConfig.SNS_SHARE_URL + "/share?id=" + id + "&type=1&jumpType=1&linkType=0" + "&invitedCode=" + invitedCode
                        + "&str=" + URLEncoder.encode(data, "UTF-8");
            }
            if ("5".equals(type)) {
                String str = "type=0&jumpType=1&linkType=0" + "&invitedCode=" + invitedCode;
                String data = "shengya!!!" + str + "shengya!!!";
                redirectUrl = WechatConfig.SNS_SHARE_URL + "/flashSale?type=5&jumpType=1&linkType=0" + "&invitedCode=" + invitedCode
                        + "&str=" + URLEncoder.encode(data, "UTF-8")
                        + "&link_name=" + URLEncoder.encode(userName, "UTF-8")
                        + "&link_icon=" + URLEncoder.encode(userUrl, "UTF-8");

            }

            return "redirect:" + redirectUrl;
        } catch (Exception e) {
            log.error("邀请赚钱分享转发错误");
        }

        return null;
    }

    @RequestMapping("/channel/pages")
    public String channelUrl(String channelCode, Integer companyId) {
        String redirectUrl = null;
        String redirectYuming1 = WechatConfig.RED_MONEY_URL;
        String redirectYuming2 = WechatConfig.RED_MONEY_COMMUNITY_URL;

        String redisKeyStr1 = "app_wechatConfigRED_MONEY_URL_url";
        String redisKeyStr2 = "app_wechatConfigRED_MONEYCommunity_URL_url";
        if (redisTemplateService.hasKey(redisKeyStr1)) {
            try {
                redirectYuming1 = redisTemplateService.getTByKey(redisKeyStr1, String.class);
            } catch (Exception e) {
                log.info("微信进行转发url{}newUrl{}", WechatConfig.RED_MONEY_URL, redirectYuming1);
            }
        }
        if (redisTemplateService.hasKey(redisKeyStr2)) {
            try {
                redirectYuming2 = redisTemplateService.getTByKey(redisKeyStr2, String.class);
            } catch (Exception e) {
                log.info("微信进行转发url{}newUrl{}", WechatConfig.RED_MONEY_COMMUNITY_URL, redirectYuming2);
            }
        }

        try {
            String str = "type=0&jumpType=1&linkType=0" + "&channelCode=" + channelCode;
            String data = "shengya!!!" + str + "shengya!!!";
            if (companyId != null) {
                if (companyId == 42 || companyId == 43) {
                    redirectUrl = redirectYuming2 + "?type=0&jumpType=1&linkType=0" + "&channelCode=" + channelCode + "&str=" + URLEncoder.encode(data, "UTF-8");

                } else {
                    redirectUrl = redirectYuming1 + "?type=0&jumpType=1&linkType=0" + "&channelCode=" + channelCode + "&str=" + URLEncoder.encode(data, "UTF-8");
                }
            } else {
                redirectUrl = redirectYuming1 + "?type=0&jumpType=1&linkType=0" + "&channelCode=" + channelCode + "&str=" + URLEncoder.encode(data, "UTF-8");
            }

            return "redirect:" + redirectUrl;

        } catch (
                Exception e) {
            log.error("渠道转发错误");
        }

        return null;
    }

    /**
     * 计算分佣获得商品
     *
     * @param userId
     * @param goods
     * @return
     */
    @PostMapping("/getGoodsScheme")
    @ResponseBody
    public ServerResponse getGoodsScheme(Long userId, @RequestBody String goods) {
        String channelId = null;
        QueryWrapper<SyChannelUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        List<SyChannelUser> syChannelUserList = syChannelUserMapper.selectList(queryWrapper);
        if (syChannelUserList != null && syChannelUserList.size() > 0) {
            channelId = syChannelUserList.get(0).getChannelId().toString();
        }
        List<AppGoods> appGoods = JSONObject.parseArray(goods, AppGoods.class);
        List<AppGoodsVo> results = taoBaoService.getAppGoodsVo(userId, appGoods, null, channelId, null);
        return ServerResponse.createBySuccess(results);
    }

    /**
     * 购买渠道来源
     *
     * @param userId
     * @param itemId
     * @return
     */
    @GetMapping("/getOrderSource")
    @ResponseBody
    public ServerResponse getOrderSource(Long userId, Long itemId) {
        if (userId != null && itemId != null) {
            List<Map<Object, Object>> map1 = (List<Map<Object, Object>>) redisTemplate.opsForList().range("app_buy_source_" + userId, 0, -1);
            if (map1.size() > 0) {
                List<String> orderSourceList = new ArrayList<>();
                for (Map orderSource : map1) {
                    if (orderSource.get("itemId").equals(itemId)) {
                        orderSourceList.add(orderSource.get("jumpType").toString());
                    }
                }
                String orderSourceStr = Joiner.on(",").join(orderSourceList);
                return ServerResponse.createBySuccess(orderSourceStr);
            }
            return ServerResponse.createByErrorMessage("无数据");
        }
        return ServerResponse.createByErrorMessage("userId  itemId不可为空");
    }

    /**
     * 粉购--商品搜索建议
     *
     * @param keyword
     * @return
     */
    @GetMapping("/getGoodsSuggest")
    @ResponseBody
    public ServerResponse getGoodsSuggest(String keyword) {
        try {
            keyword = URLEncoder.encode(keyword, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String time = "" + System.currentTimeMillis();
        String result = fenGouItemInfoService.getGoodsSuggest(keyword, time);
        List<String> suggestList = null;
        if (result != null) {
            result = JSONObject.parseObject(result).getString("data");
            suggestList = JSON.parseObject(result, List.class);
            if (suggestList == null) {
                return ServerResponse.createByErrorMessage("无数据");
            }
        } else {
            return ServerResponse.createByErrorMessage("无数据");
        }
        return ServerResponse.createBySuccess("成功", suggestList);
    }

    //拼多多推广链接生成
    @GetMapping("/getPddGoodsPromUrl")
    @ResponseBody
    public ServerResponse getPddGoodsPromUrl(Long goodsId) {
        AppUser u = getAppUser();
        if (goodsId == null) {
            return ServerResponse.createByErrorMessage("goodsId不可为空");
        }
        String url = pddSearchController.PddGoodsPromUrl(goodsId, u);
        if (url == null) {
            return ServerResponse.createByErrorMessage("无数据");
        }
        return ServerResponse.createBySuccess("成功", url);
    }

    //京东推广链接生成
    @GetMapping("/getJdGoodsPromUrl")
    @ResponseBody
    public ServerResponse getJdGoodsPromUrl(String materialUrl, String couponUrl) {
        AppUser u = getAppUser();
        String url = "";
        if (u == null) {
            url = syModuleService.getJingDongUrl(null, materialUrl, couponUrl);
        } else {
            url = syModuleService.getJingDongUrl(u.getUserId(), materialUrl, couponUrl);
        }
        return ServerResponse.createBySuccess("成功", url);
    }

    @GetMapping("/sqjdAddMoney")
    @ResponseBody
    public ServerResponse sqjdAddMoney() {
        syUserTaskService.sqjdAddMoney();
        return null;
    }

//    //朋友圈
//    @GetMapping("/getFriends")
//    @ResponseBody
//    public ServerResponse<List<ResponeFriendsResults>> getFriends(Integer pageNum, Integer pageSize) {
//        AppUser u = getAppUser();
//        if (u == null || u.getUserId() == null) {
//            return taoBaoService.getFriends(pageNum, pageSize, null, null);
//        }
//        AppUser appUser = appUserService.selectAppUserByUserId(u.getUserId());
//        if (appUser == null || appUser.getUserTaobaoAuthorization() == null || appUser.getUserTaobaoAuthorization() != 2) {
//            return taoBaoService.getFriends(pageNum, pageSize, null, null);
//        }
//
//        return taoBaoService.getFriends(pageNum, pageSize, getAppUser().getUserId(), null);
//    }

    //    /**
//     * 朋友圈分享次数
//     * @param fid
//     * @return
//     */
//    @GetMapping("/getFriendsCount")
//    @ResponseBody
//    public ServerResponse<String> getFriendsCount(Long fid) {
//
//        return taoBaoService.getFriendsCount2(fid);
//    }

    public static void main(String[] args) {
//        Map<String, Object> data = new HashMap<String, Object>();
////        data.put("nav", "3");
////        data.put("back", 20);
////        data.put("min_id", 1);
////        data.put("cid", 1);
////
////        String str = ApiUtils.getData(ApiEnum.ITEMLIST, data);
////
//////                log.info("获取好单库商品列表数据{}", str);
////        JSONObject object = JSONObject.parseObject(str);
////        AppGoods response = JsonUtils.getJsonToBean(object.toJSONString(), AppGoods.class);
////        if (response != null && response.getCode() == 1) {  //code等于1代表请求成功
////            JSONArray array = JSONArray.parseArray(object.getJSONArray("data").toJSONString());
////            List<HaoDanKuItemInfo.DataBean> bean = JsonUtils.getJsonToList(array.toJSONString(), HaoDanKuItemInfo.DataBean.class);
////
////            System.out.println(bean);
////
////        }
    }
}
